import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

// 访问到制定后端路由
const baseurl = process.env.VUE_APP_BASE_API_WEB

// 请求参数包含数组时，需要用这个
function getRequest(apiPath:any, params:any) {
  const url = baseurl + apiPath
  const req = axios.get(url, {
    params: params,
    paramsSerializer: params => {
      return qs.stringify(params, { indices: false })
    }
  })
  return req
}

// post: 后端接口获取body而不是params, 直接传json
function postRequest(apiPath:any, params:any) {
  const url = baseurl + apiPath
  const req = axios.post(url, params)
  // const req = axios.post(url, params, {
  //   // 注意传payload
  //   params: params
  // })
  return req
}

// function postRequest(apiPath:any, params:any) {
//   const url = baseurl + apiPath
//   const req = axios.post(url, qs.stringify(params, { indices: false }))
//   return req
// }

function putRequest(apiPath:any, params:any) {
  const url = baseurl + apiPath
  // var params = new URLSearchParams()
  // params.append('status', 0)
  const req = axios.put(url, qs.stringify(params, { indices: false }))
  return req
}

function deleteRequest(apiPath:any, params:any) {
  const url = baseurl + apiPath
  const req = axios.delete(url, {
    params: params,
    paramsSerializer: params => {
      return qs.stringify(params, { indices: false })
    }
  })
  return req
}

// Response interceptors
axios.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      Message({
        message: (response.status + response.statusText) || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response.data.message || 'Error'))
    } else {
      return response
    }
  },
  (error) => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export { getRequest, postRequest, putRequest, deleteRequest }
